#!/usr/bin/env python
#
# Copyright (c) 2011 David I. Lehn <dil@lehn.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os
import logging

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from idallocator import allocate_ids

# TagPoll API key
GOOGLE_API_KEY = 'AIzaSyDYDLXmYF6enuMCL_-0U1D46swcYVI5hho'

class Poll(db.Model):
    owner = db.UserProperty(
            auto_current_user_add=True,
            verbose_name="Owner")
    created = db.DateTimeProperty(
            auto_now_add=True,
            verbose_name="Created")
    question = db.StringProperty(
            required=True,
            verbose_name="Question")
    answers = db.StringListProperty(
            required=True,
            verbose_name="Answers")

class Vote(db.Model):
    created = db.DateTimeProperty(
            auto_now_add=True,
            verbose_name="Created")
    poll = db.StringProperty(
            required=True,
            verbose_name="Poll")
    vote = db.StringProperty(
            required=True,
            verbose_name="Vote")


class BaseHandler(webapp.RequestHandler):
    def v(self):
        vals = {
            'user': users.get_current_user(),
            'logout_url': users.create_logout_url('/'),
            'login_url': users.create_login_url('/')
        }
        return vals

    def render(self, path, values={}):
        """Render a template with values and return the response."""
        #self.response.headers['Content-Type'] = 'application/json'
        fullpath = os.path.join(os.path.dirname(__file__), path)
        self.response.out.write(template.render(fullpath, values))

class PollsHandler(BaseHandler):
    def get(self):
        q = Poll.all()
        q.order('-created')
        polls = q.fetch(11)

        values = {
            'polls': polls[:10]
        }

        if len(polls) == 11:
            values['start'] = polls[11].key().name 

        self.render('polls.html', values)

    def post(self):
        id = str(allocate_ids('poll', count=1).remove_count(1).ranges()[0][0])

        # set known owner else anonymous
        if users.get_current_user():
            owner = users.get_current_user()
        else:
            owner = None

        question = self.request.get('question')

        answers = self.request.get('answers')
        answers = answers.split()

        poll = Poll(key_name=id, owner=owner, question=question,
                answers=answers)
        poll.put()
        self.redirect('/polls/%s' % id)

        logging.debug("new poll: %s" % poll.key().name)


class PollHandler(BaseHandler):
    def get(self, id):
        vote_tag = self.request.get('vote')
        if vote_tag:
            # get votes
            q = Vote.all()
            q.filter('poll =', str(id))
            q.filter('vote =', vote_tag)
            # FIXME: hack hack...
            count = q.count()
            self.response.headers['Content-Type'] = 'application/json'
            self.response.out.write('{"poll":"%s","vote":"%s","votes":%d}' % (str(id), vote_tag, count))
            return

        values = self.v()
        if not values['user']:
            self.redirect(users.create_login_url(self.request.uri))
            return

        # get page
        p = Poll.get_by_key_name(id)
        values['poll'] = p
        self.render('poll.html', values)

    def post(self, id):
        if 'delete' in self.request.arguments():
            p = Poll.get_by_key_name(id)
            p.delete()
            self.redirect('/')
            return

        # set known owner else anonymous
        if users.get_current_user():
            owner = users.get_current_user()
        else:
            owner = None

        vote_tag = self.request.get('vote')
        vote = Vote(owner=owner, poll=id, vote=vote_tag)
        vote.put()

        logging.debug("new vote: %s=>%s" % (id, vote_tag))


class TagsHandler(BaseHandler):
    def get(self):
        self.render('tags.html')


class TagHandler(BaseHandler):
    def get(self, id):
        t = Tag.get_by_key_name(id)
        values = {
            'tag': t
        }
        self.render('tag.html', values)


class AddPollHandler(BaseHandler):
    def get(self):
        values = {}
        self.render('polls-add.html', values)


class AboutHandler(BaseHandler):
    def get(self):
        self.render('about.html')


class ContactHandler(BaseHandler):
    def get(self):
        self.render('contact.html')


class MainHandler(BaseHandler):
    def get(self):
        values = {}
        q = Poll.all()
        q.order('-created')
        recent = q.fetch(10)

        values = {
            'recent': recent
        }

        self.render('home.html', values)


def main():
    application = webapp.WSGIApplication([
            ('/', MainHandler),
            ('/polls/-/add', AddPollHandler),
            ('/polls/(.*)', PollHandler),
            ('/polls', PollsHandler),
            ('/tags/(.*)', TagHandler),
            ('/tags', TagsHandler),
            ('/about', AboutHandler),
            ('/contact', ContactHandler),
            ], debug=True)
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
